/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { ArkFile, ts, AstTreeUtils } from "arkanalyzer";
import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger';
import { BaseChecker, BaseMetaData } from "../BaseChecker";
import { FileMatcher, MatcherCallback, MatcherTypes } from '../../Index';
import { Defects, IssueReport } from "../../model/Defects";
import { Rule } from "../../model/Rule";
import { RuleListUtil } from "../../utils/common/DefectsList";

const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'ExplicitFunctionReturnTypeCheck');
const gMetaData: BaseMetaData = {
    severity: 1,
    ruleDocPath: "docs/explicit-function-return-type-check.md",
    description: "Require explicit return types on functions and class methods",
};
const defaultOptions: Options = {
    allowExpressions: false,
    allowTypedFunctionExpressions: true,
    allowHigherOrderFunctions: true,
    allowDirectConstAssertionInArrowFunctions: true,
    allowConciseArrowFunctionExpressionsStartingWithVoid: false,
    allowFunctionsWithoutTypeParameters: false,
    allowedNames: [],
    allowIIFEs: false,
}
interface Options {
    /** Whether to allow arrow functions that start with the `void` keyword. */
    allowConciseArrowFunctionExpressionsStartingWithVoid?: boolean;
    /** Whether to ignore arrow functions immediately returning a `as const` value. */
    allowDirectConstAssertionInArrowFunctions?: boolean;
    /** Whether to ignore function expressions (functions which are not part of a declaration). */
    allowExpressions?: boolean;
    /** Whether to ignore functions that don't have generic type parameters. */
    allowFunctionsWithoutTypeParameters?: boolean;
    /** Whether to ignore functions immediately returning another function expression. */
    allowHigherOrderFunctions?: boolean;
    /** Whether to ignore immediately invoked function expressions (IIFEs). */
    allowIIFEs?: boolean;
    /** Whether to ignore type annotations on the variable of function expressions. */
    allowTypedFunctionExpressions?: boolean;
    /** An array of function/method names that will not have their arguments or return values checked. */
    allowedNames?: string[];
}

// 定义一个接口，用于存储函数或方法的行列信息
interface LocationInfo {
    fileName: string;
    line: number;
    character: number;
}

export class ExplicitFunctionReturnTypeCheck implements BaseChecker {

    readonly metaData: BaseMetaData = gMetaData;
    public rule: Rule;
    public defects: Defects[] = [];
    public issues: IssueReport[] = [];
    private fileMatcher: FileMatcher = {
        matcherType: MatcherTypes.FILE,
    };

    public registerMatchers(): MatcherCallback[] {
        const fileMatcherCb: MatcherCallback = {
            matcher: this.fileMatcher,
            callback: this.check
        }
        return [fileMatcherCb];
    }

    public check = (target: ArkFile) => {
        if (target instanceof ArkFile) {
            const targetName = target.getName();
            if (targetName && this.getFileExtension(targetName) === ".ets") {
                return;
            }
            const code = target.getCode();
            if (!code) {
                return;
            }
            const filePath = target.getFilePath();
            const sourceFile = AstTreeUtils.getASTNode(target.getName(), code);
            const missingReturnTypes = this.checkExplicitReturnType(sourceFile);
            missingReturnTypes.forEach(info => {
                this.addIssueReportNode(info.line, info.character, filePath);
            });
        }
    }

    private getFileExtension(filePath: string): string {
        const lastDotIndex = filePath.lastIndexOf('.');
        if (lastDotIndex === -1) {
            return '';
        }
        return filePath.substring(lastDotIndex);
    }

    public checkExplicitReturnType(sourceFile: ts.SourceFile): LocationInfo[] {
        const result: LocationInfo[] = [];
        const Options: Options = this.rule && this.rule.option[0] ? this.rule.option[0] as Options : defaultOptions;
        // 遍历源文件中的所有节点
        function visit(node: ts.Node) {

            if (ts.isFunctionDeclaration(node)
                || ts.isMethodDeclaration(node)
                || ts.isArrowFunction(node)
                || ts.isFunctionExpression(node)) {

                if (Options.allowDirectConstAssertionInArrowFunctions && ts.isArrowFunction(node) && ts.isDeleteExpression(node)) {
                    return;
                }
                if (Options.allowExpressions && ts.isArrowFunction(node)) {
                    return;
                }
                if (Options.allowTypedFunctionExpressions && ts.isTypeOfExpression(node)) {
                    return;
                }
                if (Options.allowConciseArrowFunctionExpressionsStartingWithVoid && ts.isVoidExpression(node)) {
                    return;
                }
                if (Options.allowIIFEs && ts.isArrowFunction(node) && ts.isPrefixUnaryExpression(node) && ts.isPostfixUnaryExpression(node)) {
                    return;
                }

                if (Options.allowFunctionsWithoutTypeParameters && !node.typeParameters) {
                    return;
                }
                // 检查是否有返回类型注解
                if (!node.type) {
                    const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
                    if (ts.isArrowFunction(node)) {
                       // 找到箭头函数的 => 符号的位置
                       const arrowToken = (node as ts.ArrowFunction).equalsGreaterThanToken;
                       if (arrowToken) {
                           const { line: arrowLine, character: arrowChar } = sourceFile.getLineAndCharacterOfPosition(arrowToken.getStart());
                           result.push({
                               fileName: sourceFile.fileName,
                               line: arrowLine + 1, // 行号从1开始
                               character: arrowChar + 1 // 列号从1开始
                           });
                       }
                    } else {
                        result.push({
                            fileName: sourceFile.fileName,
                            line: line + 1, // 行号从1开始
                            character: character + 1 // 列号从1开始
                        });
                    }

                }
            }
            ts.forEachChild(node, visit);
        }
        visit(sourceFile);
        return result;
    }

    // 检查是否是箭头函数
    public isArrowFunction(code: string): boolean {
        const arrowFunctionRegex = /(\w+\s*=\s*)?\(\s*[^)]*\s*\)\s*=>\s*(\{[\s\S]*\}|[^;]+)/;
        return arrowFunctionRegex.test(code);
    }

    private addIssueReportNode(line: number, startCol: number, filePath: string) {
        const severity = this.rule.alert ?? this.metaData.severity;
        const fixKey = line + '%' + startCol + '%' + this.rule.ruleId;
        const mergeKey = filePath + '%' + fixKey + '%' + this.metaData.description;
        const defect = new Defects(line, startCol, this.metaData.description, severity, this.rule.ruleId,
            mergeKey, this.metaData.ruleDocPath, true, false, false, fixKey)
        this.issues.push(new IssueReport(defect, undefined));
        RuleListUtil.push(defect);
    }
}
